package cm.util.chart.action;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.hibernate.HibernateException;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.data.time.Day;
import org.jfree.data.time.Month;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.xy.XYDataset;

import cm.util.chart.TimeSeriesChart;
import cm.util.exception.MessageException;
import cm.util.hibernate.HibernateSessionFactory;

import com.opensymphony.xwork2.ActionSupport;

public class TimeSeriesChartSQLAction extends ActionSupport {

	private static final long serialVersionUID = -6381994023987145818L;

	private String title;

	private String timeLabel;

	private String valueLabel;

	private int width;

	private int height;

	private String info;
	
	private String type;

	public TimeSeriesChartSQLAction(String title, String timeLabel,
			String valueLabel, int width, int height, String info,String type) {
		this.title = title;
		this.timeLabel = timeLabel;
		this.valueLabel = valueLabel;
		this.width = width;
		this.height = height;
		this.info = info;
		this.type=type;
	}

	@Override
	public String execute() throws Exception {
		HttpServletResponse response = ServletActionContext.getResponse();
		JFreeChart chart = null;
		
		if("month".equalsIgnoreCase(type)){
			chart=TimeSeriesChart.createChart(title, timeLabel,
					valueLabel, addMonthTime(info),"yyyy-MM");
		}else if("day".equalsIgnoreCase(type)){
			chart=TimeSeriesChart.createChart(title, timeLabel,
					valueLabel, addDayTime(info),"yyyy-MM-dd");
		}

		try {
			ChartUtilities.writeChartAsJPEG(response.getOutputStream(), chart,
					width, height);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 按照月份显示折现
	 * @param info
	 * @return
	 */
	private XYDataset addMonthTime(String info) {
		String[] strs = info.split(";");
		TimeSeriesCollection timeseriescollection = new TimeSeriesCollection();
		Session session = HibernateSessionFactory.getSession();
		for (String str : strs) {
			String[] values = str.split(":");
			if (values.length != 2) {
				StringBuffer buffer = new StringBuffer();
				for (String value : values) {
					buffer.append(value);
				}
				throw new MessageException("数据异常！" + buffer);
			}
			TimeSeries timeseries = new TimeSeries(values[0],
					org.jfree.data.time.Month.class);
			String sql = values[1];
			try {
				SQLQuery query = session.createSQLQuery(sql);
				List<Object[]> list = query.list();
				for (Object[] obs : list) {
					if (obs.length != 3) {
						StringBuffer buffer = new StringBuffer();
						for (Object ob : obs) {
							buffer.append(ob + "  ");
						}
						throw new MessageException("数据不合法!  " + buffer);
					}
					Integer month=Integer.parseInt(obs[0].toString());
					Integer year=Integer.parseInt(obs[1].toString());
					if(month<=12&&month>0&&year>0&&year<9999){
						timeseries.add(new Month(month, year), Integer
								.parseInt(obs[2].toString()));
					}
				}
			} catch (HibernateException e) {
				e.printStackTrace();
			}
			timeseriescollection.addSeries(timeseries);
		}
		return timeseriescollection;
	}
	
	/**
	 * 按照日期显示折现
	 * @param info
	 * @return
	 */
	private XYDataset addDayTime(String info) {
		String[] strs = info.split(";");
		TimeSeriesCollection timeseriescollection = new TimeSeriesCollection();
		Session session = HibernateSessionFactory.getSession();
		for (String str : strs) {
			String[] values = str.split(":");
			if (values.length != 2) {
				StringBuffer buffer = new StringBuffer();
				for (String value : values) {
					buffer.append(value);
				}
				throw new MessageException("数据异常！" + buffer);
			}
			TimeSeries timeseries = new TimeSeries(values[0],
					org.jfree.data.time.Day.class);
			String sql = values[1];
			try {
				SQLQuery query = session.createSQLQuery(sql);
				List<Object[]> list = query.list();
				for (Object[] obs : list) {
					if (obs.length != 4) {
						StringBuffer buffer = new StringBuffer();
						for (Object ob : obs) {
							buffer.append(ob + "  ");
						}
						throw new MessageException("数据不合法!  " + buffer);
					}
					Integer day=Integer.parseInt(obs[0].toString());
					Integer month=Integer.parseInt(obs[1].toString());
					Integer year=Integer.parseInt(obs[2].toString());
					if(day<=31&day>0&month<=12&&month>0&&year>0&&year<9999){
						timeseries.add(new Day(day,month, year), Integer
								.parseInt(obs[3].toString()));
					}
				}
			} catch (HibernateException e) {
				e.printStackTrace();
			}
			timeseriescollection.addSeries(timeseries);
		}
		return timeseriescollection;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getTimeLabel() {
		return timeLabel;
	}

	public void setTimeLabel(String timeLabel) {
		this.timeLabel = timeLabel;
	}

	public String getValueLabel() {
		return valueLabel;
	}

	public void setValueLabel(String valueLabel) {
		this.valueLabel = valueLabel;
	}

	public int getWidth() {
		return width;
	}

	public void setWidth(int width) {
		this.width = width;
	}

	public int getHeight() {
		return height;
	}

	public void setHeight(int height) {
		this.height = height;
	}

	public String getInfo() {
		return info;
	}

	public void setInfo(String info) {
		this.info = info;
	}

}
